package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.business;

import com.gzhryc.common.MatrixToImageWriter;
import com.gzhryc.common.NumberTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.ECouponType;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.business.dao.db.CouponActivity;
import com.gzhryc.shared_device.oem.code.business.dao.enums.CouponActivityEnum;
import com.gzhryc.shared_device.oem.code.business.services.CouponActivityService;
import com.gzhryc.shared_device.oem.code.business.services.dto.CouponActivitySearch;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CouponActivityController {

    static Logger log = Logger.getLogger(CouponActivityController.class);

    @Route(value = { "/business/coupon_activity/list.html" })
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList",CouponActivityEnum.State.values());
        request.setAttribute("typeList", CouponActivityEnum.Type.values());
        request.setAttribute("couponTypeList", ECouponType.values());
        List<EBusinessType> businessTypeList = new ArrayList<>();
        businessTypeList.add(EBusinessType.BXSCN_SHOP);
        businessTypeList.add(EBusinessType.CDB);
        businessTypeList.add(EBusinessType.CDCZ);
        request.setAttribute("businessTypeList",businessTypeList);
        return "/business/coupon_activity/list.html";
    }

    @Route(value = "/business/coupon_activity/list.data")
    public ListResult<CouponActivity> listData(HttpServletRequest request) {
        ListResult<CouponActivity> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            CouponActivitySearch search = WebUtils.getParameter(request, CouponActivitySearch.class);
            search.setUserId(loginUser.getId());
            Integer pageNo = WebUtils.getInteger(request, "page", 1);
            Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

            result.getBody().setTotal(CouponActivityService.self().countJoinBySearch(search));
            result.getBody().setData(CouponActivityService.self().findJoinBySearch(search, pageNo, pageLimit));

            if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        }
        return result;
    }

    @Route(value = { "/business/coupon_activity/add.html" })
    public String add(HttpServletRequest request) {
        request.setAttribute("useLimitList", CouponActivityEnum.UseLimit.values());
        request.setAttribute("useRangeList", CouponActivityEnum.UseRange.values());
        request.setAttribute("typeList", CouponActivityEnum.Type.values());
        request.setAttribute("couponTypeList", ECouponType.values());
        List<EBusinessType> businessTypeList = new ArrayList<>();
        businessTypeList.add(EBusinessType.BXSCN_SHOP);
        businessTypeList.add(EBusinessType.CDB);
        businessTypeList.add(EBusinessType.CDCZ);
        request.setAttribute("businessTypeList",businessTypeList);
        request.setAttribute("type",CouponActivityEnum.Type.Scan.index());
        Date startDate = new Date();      //默认一个月
        Date endDate = DateUtils.addDays(startDate,30);
        request.setAttribute("startDate", startDate);
        request.setAttribute("endDate", endDate);
        return "/business/coupon_activity/edit.html";
    }

    @Route(value = { "/business/coupon_activity/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败，请稍后再试");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            CouponActivity couponActivity = WebUtils.getParameter(request, CouponActivity.class);
            try {
                couponActivity.setUserId(loginUser.getId());
                Date startDate = WebUtils.getDate(request, "startDate");
                Date endDate = WebUtils.getDate(request, "endDate");
                if (startDate != null && endDate != null) {
                    couponActivity.setStartDate(startDate);
                    couponActivity.setEndDate(endDate);
                } else {
                    result.setMsg("请填写活动有效时间");
                    return result;
                }

                Double minimumChargeStr = WebUtils.getDouble(request, "minimumChargeStr");
                if (minimumChargeStr != null) {
                    couponActivity.setMinimumCharge(NumberTools.changeMoney(minimumChargeStr));
                }
                Double couponMoneyStr = WebUtils.getDouble(request, "couponMoneyStr");
                if (couponMoneyStr != null) {
                    couponActivity.setCouponMoney(NumberTools.changeMoney(couponMoneyStr));
                }
                if (CouponActivityService.self().add(couponActivity)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/business/coupon_activity/info.html" })
    public String info(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        CouponActivity couponActivity = CouponActivityService.self().getJoinById(id);
        WebUtils.setAttribute(request,couponActivity);
        return "/business/coupon_activity/info.html";
    }

    @Route(value = { "/business/coupon_activity/update.html" })
    public String update(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        CouponActivity couponActivity = CouponActivityService.self().getJoinById(id);
        WebUtils.setAttribute(request,couponActivity);

        request.setAttribute("useLimitList", CouponActivityEnum.UseLimit.values());
        request.setAttribute("useRangeList", CouponActivityEnum.UseRange.values());
        request.setAttribute("typeList", CouponActivityEnum.Type.values());
        request.setAttribute("couponTypeList", ECouponType.values());
        List<EBusinessType> businessTypeList = new ArrayList<>();
        businessTypeList.add(EBusinessType.BXSCN_SHOP);
        businessTypeList.add(EBusinessType.CDB);
        businessTypeList.add(EBusinessType.CDCZ);
        request.setAttribute("businessTypeList",businessTypeList);
        return "/business/coupon_activity/edit.html";
    }

    @Route(value = { "/business/coupon_activity/update.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            CouponActivity couponActivity = WebUtils.getParameter(request, CouponActivity.class);
            try {
                couponActivity.setUserId(loginUser.getId());

                Date startDate = WebUtils.getDate(request, "startDate");
                Date endDate = WebUtils.getDate(request, "endDate");
                if (startDate != null && endDate != null) {
                    couponActivity.setStartDate(startDate);
                    couponActivity.setEndDate(endDate);
                } else {
                    result.setMsg("请填写活动有效时间");
                    return result;
                }

                Double minimumChargeStr = WebUtils.getDouble(request, "minimumChargeStr");
                if (minimumChargeStr != null) {
                    couponActivity.setMinimumCharge(NumberTools.changeMoney(minimumChargeStr));
                }
                Double couponMoneyStr = WebUtils.getDouble(request, "couponMoneyStr");
                if (couponMoneyStr != null) {
                    couponActivity.setCouponMoney(NumberTools.changeMoney(couponMoneyStr));
                }
                if (CouponActivityService.self().updateNotNull(couponActivity)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/business/coupon_activity/qrcode.html" })
    public String qrcode(HttpServletRequest request) {
        Long activityId = WebUtils.getLong(request, "activityId");
        if (activityId != null) {
            CouponActivity couponActivity = CouponActivityService.self().getJoinById(activityId);
            if (couponActivity != null) {
                String httpDomain = PropertyTools.get().getString("httpDomain");
                String url = httpDomain + "/business/coupon_activity/" + couponActivity.getId();
                request.setAttribute("url", url);
            }
        }
        return "/business/coupon_activity/qrcode.html";
    }

    @Route(value = { "/business/coupon_activity/qrcode.jpg" })
    public void qrcodeImg(HttpServletRequest request, HttpServletResponse response) {
        Long activityId = WebUtils.getLong(request, "activityId");
        if (activityId != null) {
            CouponActivity couponActivity = CouponActivityService.self().getJoinById(activityId);
            if (couponActivity != null) {
                try {
                    String httpDomain = PropertyTools.get().getString("httpDomain");
                    String url = httpDomain + "/business/coupon_activity/" + couponActivity.getId();
                    WebUtils.exportJPEG(response);
                    MatrixToImageWriter.writeToStream(url, 400, 300, "jpeg", response.getOutputStream());
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @Route(value = { "/business/coupon_activity/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Long id = WebUtils.getLong(request,"id");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            CouponActivity couponActivity = CouponActivityService.self().getJoinById(id);
            if(couponActivity != null && couponActivity.getUserId().equals(loginUser.getId())) {
                try {
                    if (CouponActivityService.self().deleteById(id)) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            }else{
                result.setCode(DtoConstants.NOT_POWER,"无权限删除");
            }
        }
        return result;
    }
}
